<?php

// +----------------------------------------------------------------------
// | 通知
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\ucenter;

use app\common\event\Base;
use app\common\event\Job;
use app\event\ucenter\Email as EmailEvent;
use app\event\ucenter\Sms as SmsEvent;
use app\model\ucenter\Sms as SmsModel;
use app\model\ucenter\User as UserModel;
use app\model\store\Order as OrderModel;
use app\wechat\event\WechatTemplate as WechatTemplateEvent;
use app\event\app\Device as DeviceEvent;
use think\Exception;
use app\event\ucenter\Message as MessageEvent;
use think\facade\Config;
use think\facade\Log;
use think\facade\Session;
use app\model\pos\PosOrder as PosOrderModel;
use app\model\store\DepositOrder as DepositOrderModel;

class Notice extends Base
{
    /**
     * 发送验证码
     * @param array $param
     * @param null|UserModel $user
     * @param string $channel
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public static function safeCode($param, $user = null, $channel = 'mobile')
    {
        try {
            $param['code'] = rand(1000, 9999);
            if ('mobile' == $channel) {
                // 短信
                $data = SmsEvent::send($param, $user);
            } else {
                // 发送邮件
                $data = EmailEvent::send($param, $user);
            }
            if ($data['code'] != 0) {
                throw new Exception($data['message'], $data['code']);
            }
            // 保存验证码
            $user_code = [
                'code' => $param['code'],
                // 验证通过可用次数
                'useful_times' => 3,
                'expires_time' => time() + 600,
                'try' => 3];
            if ('mobile' == $channel) {
                // 短信
                $user_code['client'] = $param['mobile'];
            } else {
                // 发送邮件
                $user_code['client'] = $param['email'];
            }
            $id = $param['id'] ?? '';

            Session::set('user_code_' . $id, $user_code);

            $data['message'] = '发送成功';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();

        }
        return $data;
    }


    /**
     * 检查验证码正确
     * @param $code
     * @return mixed
     * @throws Exception
     * @author  : 微尘 <yicmf@qq.com>
     */
    public static function checkCode($code, $id = '')
    {
        if (Session::has('user_code_' . $id)) {
            //验证码有效次数为一次
            $user_code = Session::pull('user_code_' . $id);
            if ($user_code['expires_time'] < time()) {
                throw new  Exception('验证码超时，请重新获取');
            }
            if ($user_code['code'] != $code) {
                if ($user_code['try'] > 1) {
                    $user_code['try'] = $user_code['try'] - 1;
                    Session::set('user_code_' . $id, $user_code);
                }
                throw new  Exception('验证码填写错误');
            }
            $user_code['useful_times'] = $user_code['useful_times'] - 1;
            if ($user_code['useful_times'] > 0) {
                Session::set('user_code_' . $id, $user_code);
            }
            // 返回接收端
            return $user_code['client'];
        } else {
            throw new Exception('请重新获取验证码');
        }
    }

    /**
     * 检查验证码正确
     * @param $code
     * @return mixed
     * @throws Exception
     * @author  : 微尘 <yicmf@qq.com>
     */
    public static function checkDbCode($code, $token)
    {
        $sms = SmsModel::where('token', $token)->whereTime('create_time', '-10 minute')->find();
        if ($sms) {
            if ($sms['times'] > 3) {
                throw new Exception('验证次数过多，请重新获取验证码');
            }
            $sms['times'] = $sms['times'] + 1;
            $sms->save();

            if ($code == $sms['code']) {
                return $sms['mobile'];
            } else {
                throw new Exception('验证码填写错误');
            }
        } else {
            throw new Exception('请重新获取验证码');
        }
    }

    /**
     * 发送消息
     * @param array $param
     * @param UserModel|null $toUser
     * @param UserModel|null $fromUser
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public static function send($param, $toUser = null, $fromUser = null)
    {
        try {
            if (isset($param['join_queue'])) {
                unset($param['join_queue']);
                if (!is_null($toUser)) {
                    $param['to_user_id'] = $toUser['id'];
                }
                if (!is_null($fromUser)) {
                    $param['from_user_id'] = $fromUser['id'];
                } elseif (is_null($fromUser) && !isset($param['from_user_id'])) {
                    $param['from_user_id'] = Config::get('ucenter.system_notice_from_user_id');
                }
                // 加入队列
                Job::addTask('notice_send', $param);
                $data['code'] = 0;
                $data['message'] = '加入队列';
            } else {
                if (is_null($toUser) && isset($param['to_user_id'])) {
                    $toUser = UserModel::where('id', $param['to_user_id'])->find();
                    if (!$toUser) {
                        throw new Exception('消息用户不存在');
                    }
                }
                if (is_null($fromUser) && isset($param['from_user_id'])) {
                    $fromUser = UserModel::where('id', $param['from_user_id'])->find();
                } elseif (is_null($fromUser)) {
                    $fromUser = UserModel::where('id', 1)->find();
                }
                $message = new MessageEvent();
                $device = new DeviceEvent();

                switch ($param['type']) {
                    case 'deposit':
                        // 站内信
                        $param['title'] = '升级中级合伙人成功';
                        $param['content'] = '恭喜您成功升级中级合伙人，我们为您准备了价值498元的升级活动礼包，点击进入补充收件地址我们尽快为您发货。';
                        $data = $message->send($param, $toUser, $fromUser);
                        // 发送APP推送
                        $device->pushToSingleUser($param, $toUser, $fromUser);
                        // 微信公众号提醒
                        break;
                    case 'rebate_pdd':
                        // pdd到了
                        // 站内信
                        $param['title'] = '拼多多返利可用';
                        $param['content'] = '您的拼多多返利可用，预计返佣' . round($param['good']['min_group_price'] * $param['good']['promotion_rate'], 2) . '元';
                        $param['data'] = $param['good'];
                        $data = $message->send($param, $toUser, $fromUser);
                        // 发送APP推送
                        $device->pushToSingleUser($param, $toUser, $fromUser);
                        // 微信公众号提醒

                        //Qa5PspnbrF_0aZ02UePEdsZj-m5TR23MrKvDcRgdO1s
                        break;
                    case 'cash_success':
                        // 提现成功
                        $order = OrderModel::where('id', $param['order_id'])->where('status', '>', 1)->find();
                        if ($order) {
                            // 发送短信|邮件通知
                            if ('email' == $order['notice_service']) {
                                // 邮件通知
                                $param['email'] = $order['email'];
                                $data = EmailEvent::send($param);
                            } elseif ('mobile' == $order['notice_service']) {
                                // 短信通知
                                $param['mobile'] = $order['contact'];
                                $data = SmsEvent::send($param);
                            } else {
                                throw new Exception('没有提醒');
                            }
                        } else {
                            throw new Exception('订单不存在');
                        }
                        break;
                    case 'send_deposit':
                        // 下单后订单发货
                        $order = DepositOrderModel::where('id', $param['relation_id'])->find();
                        if ($order) {
                            // 发送短信|邮件通知
                            $param['title'] = '发货通知';
                            $param['content'] = '您的礼包已经发货，快递公司：'.$order['express_name'].'快递单号：'.$order['express_sn'];
                            $data = $message->send($param, $toUser, $fromUser);
                            $re = $device->pushToSingleUser($param, $toUser, $fromUser);
                        } else {
                            throw new Exception('订单不存在');
                        }
                        break;
                    case 'order_send':
                        // 下单后订单发货
                        $order = OrderModel::where('id', $param['relation_id'])->where('status', 3)->find();
                        if ($order) {

                            // 发送短信|邮件通知
                            $param['title'] = '发货通知';
                            $param['content'] = '您购买的商品商家已经发货';
                            $data = $message->send($param, $toUser, $fromUser);
                            $re = $device->pushToSingleUser($param, $toUser, $fromUser);
                            // 发送短信|邮件通知
//								if ('email' == $order['notice_service']) {
//									// 邮件通知
//									$param['email'] = $order['email'];
//									$data = EmailEvent::send($param);
//								} elseif ('mobile' == $order['notice_service']) {
//									// 短信通知
//									$param['mobile'] = $order['contact'];
//									$data = SmsEvent::send($param);
//								} else {
//									throw new Exception('没有提醒');
//								}
                        } else {
                            throw new Exception('订单不存在');
                        }
                        break;
                    case 'user_pay_order':
                        // 售出商品
                        $order = OrderModel::find($param['order_id']);
                        if ($order) {
                            // 发送短信|邮件通知
                            $param['title'] = '商品售出';
                            $param['content'] = '成交价：' . $order['real_amount'] . '日元';
                            $message->send($param, $toUser, $fromUser);
                            $device->pushToSingleUser($param, $toUser, $fromUser);
                            //							$param['email'] = $toUser['email'];
                            //							$data = EmailEvent::send($param);
                        } else {
                            throw new Exception('订单不存在');
                        }
                        break;
                    case 'monitor_check':
                        // 监听测试
                        $data = $device->pushToSingleUser($param, $toUser, $fromUser);
                        break;
                    case 'complaint_add_order':
                        // 订单投诉
                        $order = OrderModel::find($param['order_id']);
                        if ($order) {
                            // 发送短信|邮件通知
                            $param['title'] = '订单投诉';
                            $param['content'] = '您有订单投诉，请及时处理';
                            $message->send($param, $toUser, $fromUser);
                            $device->pushToSingleUser($param, $toUser, $fromUser);
                            //							$param['email'] = $toUser['email'];
                            //							$data = EmailEvent::send($param);
                        } else {
                            throw new Exception('订单不存在');
                        }

                        break;
                    case 'pay_order':
                        // 订单下单
                        $order = PosOrderModel::find($param['order_id']);
                        if ($order) {
                            // 发送短信|邮件通知
                            $param['title'] = '支付成功';
                            $param['content'] = '您的订单支付成功';
                            $re = $message->send($param, $toUser, $fromUser);
//								$device->pushToSingleUser($param, $toUser, $fromUser);
                            //							$param['email'] = $toUser['email'];
                            //							$data = EmailEvent::send($param);
                        } else {
                            throw new Exception('订单不存在');
                        }

                        break;
                    case 'settlement_finish':
                        // 结算完毕
                        $message->send($param, $toUser, $fromUser);
                        $device->pushToSingleUser($param, $toUser, $fromUser);
                        $param['email'] = $toUser['email'];
                        $data = EmailEvent::send($param, $toUser);
                        // 短信通知
                        //                            $param['mobile'] = $toUser['mobile'];
                        //                            $data = SmsEvent::send($param);
                        break;
                    case 'auth':
                        // 用户实名认证审核结果
                        $message->send($param, $toUser, $fromUser);
                        $device->pushToSingleUser($param, $toUser, $fromUser);
                    case 'cancel_order':
                        // 取消订单
                        $message->send($param, $toUser, $fromUser);
                        $device->pushToSingleUser($param, $toUser, $fromUser);
                        break;
                    case 'feedback_reply':
                        // 意见反馈
                        $message->send($param, $toUser, $fromUser);
//                        $device->pushToSingleUser($param, $toUser, $fromUser);
                        break;
                    case 'stock_alarm':
                        // 发送短信|邮件通知
                        // 邮件通知
                        $param['email'] = $toUser['email'];
                        $data = EmailEvent::send($param, $toUser);
                        // 短信通知
                        //                            $param['mobile'] = $toUser['mobile'];
                        //                            $data = SmsEvent::send($param);
                        break;
                    case 'down_sale_agent':
                        // 代理商品因为修改信息下架  发送短信|邮件通知
                        // 邮件通知
                        $param['title'] = '供货商修改信息，代理商品下架';
                        $param['content'] = $param['reason'];
                        $message->send($param, $toUser, $fromUser);
                        $device->pushToSingleUser($param, $toUser, $fromUser);
                        if ($toUser['email']) {
                            $param['email'] = $toUser['email'];
                            $data = EmailEvent::send($param, $toUser);
                        }
                        break;

                    case 'admin_notice':
                        // 邮件通知
                        if (in_array('email', $param['types'])) {
                            $data = EmailEvent::send($param, $toUser);
                        }
                        // 站内信
                        if (in_array('message', $param['types'])) {
                            $data = $message->send($param, $toUser, $fromUser);
                        }
                        // APP
                        if (in_array('app', $param['types'])) {
                            $data = $device->pushToSingleUser($param, $toUser, $fromUser);
                        }
                        break;

                    default:
                        // 默认消息
                        $data = $message->send($param, $toUser, $fromUser);
                        break;
                }


                $data['code'] = 0;
            }
        } catch (\Exception $e) {
            // 回滚事务
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 后台发送消息
     * @param array $param
     * @param UserModel $admin
     * @param string $type
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     * @datetime: 2020/1/3 20:10
     */
    public static function sendByAdmin($param, $admin)
    {
        try {
            if (!isset($param['types']) || !count($param['types'])) {
                throw new Exception('请选择接收方式');
            }
            $users = UserModel::where('status', 1);
            if (0 == $param['to_type']) {
                // 发送单个消息
                $users = $users->where('id', $param['user_id']);
            } elseif (1 == $param['to_type']) {
                // 根据用户手机号
                $users = $users->where('mobile', $param['mobile'])->where('auth_mobile', 1);
            } elseif (2 == $param['to_type']) {
                // 根据用户邮箱
                $users = $users->where('email', $param['email'])->where('auth_email', 1);
            } elseif (3 == $param['to_type']) {
                // 根据用户组发送
                $users = $users->where('user_grade_id', $param['user_grade_id']);
            } elseif (4 == $param['to_type']) {
                // VIP
                $users = $users->where('is_vip', 1);
            } else {
                // 全部
                $users = $users->where('store_id', '>', 1);
            }
            $count = 0;
            $error = 0;
            $users = $users->limit(10000 * ($param['user_page'] - 1), 10000 * $param['user_page'])->select();

            if (!$users) {
                throw new Exception('没有发现接收消息用户');
            }
            $param['type'] = 'admin_notice';
            foreach ($users as $index => $toUser) {
                if ($toUser) {
                    $types = $param['types'];
                    foreach ($types as $type) {
                        $param['types'] = [$type];
                        $re = self::send($param, $toUser, $admin);
                        if ($re['code'] === 0) {
                            $count++;
                        } else {
                            $error++;
                        }
                    }
                }
            }

            $data['data'] = $count;
            $data['message'] = '成功发送' . $count . '条消息' . ($error ? ('失败' . $error . '条') : '');

            // 返回订单数据
            $data['code'] = 0;
        } catch (\Exception $e) {
            // 回滚事务
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    public function taskSendJob($data)
    {

    }
}
